package com.koicarp.agent.example.chatmemery;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageType;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liuxia
 * @CreateTime: 2025/9/14 下午3:16
 * @Description:
 *      持久化聊天缓存存储
 *      实际场景应该结合redis做用户聊天信息处理
 */
@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {

    private ChatMessageService chatMessageService;

    PersistentChatMemoryStore(ChatMessageService chatMessageService) {
        this.chatMessageService = chatMessageService;
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        List<ChatMessage> messages = new ArrayList<>();
        List<CustomChatMessage> msgs = chatMessageService.getMessageListById(Integer.valueOf(memoryId.toString()));
        for (CustomChatMessage msg : msgs) {
            if (msg.getType().equals(1)) {
                UserMessage userMessage = UserMessage.from(msg.getMessage());
                messages.add(userMessage);
            } else if (msg.getType().equals(2)){
                AiMessage aiMessage = AiMessage.from(msg.getMessage());
                messages.add(aiMessage);
            }
        }
        return messages;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        // list 保存的是最新的全部信息，包含用户这次的聊天信息，只需要获取最新一条保存的数据库
        ChatMessage latestMsg = list.get(list.size() - 1);
        ChatMessageType typeEnum = latestMsg.type();
        Integer type = 1;
        String message = "";
        if (typeEnum.equals(ChatMessageType.AI)) {
            type = 2;
            AiMessage aiMessage = (AiMessage) latestMsg;
            message = aiMessage.text();
        } else if (typeEnum.equals(ChatMessageType.USER)) {
            type = 1;
            UserMessage userMessage = (UserMessage) latestMsg;
            message = userMessage.singleText();
        }
        chatMessageService.save(Integer.valueOf(memoryId.toString()), type, message);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        chatMessageService.delByUserId(Integer.valueOf(memoryId.toString()));
    }
}
